"use strict";
var x;
require(["drag", "scroll", "base"], function(drag, scroll, base){
    // 添加滚动条
    x = scroll("#scroll", {
        width: 400,
        height: 300,
        dragSwitch: false
    });

    // 按住空格时可以改变滚动的方向
    document.onkeydown = function(event){
        if(event.key == " ")
        {
            console.log("a down");
            x.scroll = "x";
        }
    }
    
    document.onkeyup = function(event){
        if(event.key == " ")
        {
            console.log("a up");
            x.scroll = "y";
        }
    }

    // 嵌套事件
    window.yyy = scroll("#scrollInner", {
        height: 50,
        width: 400,
        scroll: "x"
    });

    // 任意拖动
    window.dr = drag("#drag1");

    var context = {
        name: "drag"
    }

    // 限制竖直移动
    drag("#drag2", {
        // 除了添加move还有down和up事件回调
        // 回调的第一个参数指向drag实例
        // 第三个参数可以指定事件调用的this指向，不写默认为drag实例
        // 如果有第三个参数必须有第二个参数
        move: function(drag)
        {
            drag.style.left = drag.left;
        }
    }, context);

    // 限制水平移动
    drag("#drag3", {
        move: function()
        {
            this.style.top = this.top;
        }
    });

    // 限制移动距离
    drag("#drag4", {
        move: function()
        {
            this.style.top = base.scope(0, 100, this.style.top);
            this.style.left = base.scope(0, 100, this.style.left);
        }
    });
});

// 模拟网络数据
var data = {
    "001": {
        name: "张三",
        age: "13"
    },
    "002": {
        name: "李四",
        age: "15"
    },
    "003": {
        name: "王五",
        age: "18"
    },
    "004": {
        name: "张三a",
        age: "13"
    },
    "005": {
        name: "李四a",
        age: "15"
    },
    "006": {
        name: "王五a",
        age: "18"
    }
}

require(["vue", "base", "jquery"], function(Vue, base){
    var app = new Vue({
        el: "#app",
        data: {
            userPool: {}
        }
    });

    // 第一个参数是数据存储的位置
    // 第二个参数是存储数据的模板
    // 第三个参数是获取数据函数，该函数第一个参数为对象唯一标识的数组
    // 第四个参数是设置对象的方法
    var userPool = base.pool(app.userPool, {
        name: "加载中...",
        age: "加载中..."
    }, function(idList){
        // 模拟一下网络延迟
        setTimeout(function(){
            Lyx.each(idList, function(index, id){
                userPool.setModel(id, data[id]);
            });
        }, Lyx.random(100, 1000));
    }, Vue.set);

    // 逐个获取
    userPool.getId("001");
    userPool.getId("003");
    userPool.getId("005");

    // 收集后统一获取，减少请求次数
    Lyx.each(["002", "004", "006"], function(index, id){
        userPool.setId(id);
    });
    userPool.getList();
});

var center;
require(["alert", "ui"], function(alert, ui, Lyx){
    var theme = alert.theme.dnf();
    center = alert(theme);

    ui.$("#alert").onclick = function(){
        center.msg({
            title: "赛丽亚",
            content: `我叫赛丽亚！我叫赛丽亚！我叫赛丽亚！
            我叫赛丽亚！我叫赛丽亚！我叫`
        });

        center.msg({
            title: "赛丽亚",
            content: `我是来帮助那些需要帮助的勇士的！
            我是来帮助那些需要帮助的勇士的！
            我是来帮助那些需要帮助的勇士的！
            我是来帮助那些需要帮助的勇士的！
            我是来帮助那些需要帮助的勇士的！
            我是来帮助那些需要帮助的勇士的！
            我是来帮助那些需要帮助的勇士的！
            `
        });

        center.msg({
            title: "赛丽亚",
            content: `如果有需要我一定会帮助您的！
            如果有需要我一定会帮助您的！
            如果有需要我一定会帮助您的！
            如果有需要我一定会帮助您的！
            如果有需要我一定会帮助您的！
            如果有需要我一定会帮助您的！如果有需要我一定会帮助您的！
            如果有需要我一定会帮助您的！如果有需要我一定会帮助您的！
            如果有需要我一定会帮助您的！如果有需要我一定会帮助您的！
            如果有需要我一定会帮助您的！如果有需要我一定会帮助您的！`
        });
    }
});

var chrome = {
    extension: {
        sendMessage: function(msg)
        {
            console.log(msg);
        },
        onMessage: {
            addListener: function(callback){
                callback();
            }
        }
    }
}

require(["drag", "ui"], function(drag, ui){

    var selectPop = Lyx.createClass(function(p2t){
        var body = ui.$("body[0]");
        p2t.init = function(pointer)
        {
            this.pointer = pointer;

            this.index = 0;

            this.window = ui.addNode(body, "div", "innerEnd", {
                class: "Lyxwindow",
                style: {
                    display: "none"
                }
            });

            var title = ui.addNode(this.window, "div", "innerEnd", {
                class: "Lyxtitle"
            });

            ui.addNode(title, "strong", "innerEnd").innerHTML = "元素选择器";

            this.close = ui.addNode(title, "span", "innerEnd")
            this.close.innerHTML = "×";

            this.content = ui.addNode(this.window, "div", "innerEnd", {
                style: {
                    height: 85
                }
            });

            ui.addNode(this.content, "div", "innerEnd", {
                style: {
                    paddingLeft: 10,
                    height: 40,
                    lineHeight: 40
                }
            }).innerHTML = "拖动圆点指针选择元素层级";

            this.view = ui.addNode(this.content, "div", "innerEnd", {
                class: "Lyxview"
            });

            var pointer = ui.addNode(this.content, "div", "innerEnd", {
                class: "Lyxpointer"
            });

            ui.addNode(pointer, "div", "innerEnd");

            var button = ui.addNode(this.window, "div", "innerEnd", {
                class: "Lyxbutton"
            });

            this.select = ui.addNode(button, "div", "innerEnd", {
                class: "Lyxselect"
            });
            this.select.innerHTML = "选择其他元素";

            this.cancelSelect = ui.addNode(button, "div", "innerEnd", {
                class: "Lyxselect",
                style: {
                    display: "none"
                }
            });
            this.cancelSelect.innerHTML = "取消选择模式";

            this.intercept = ui.addNode(button, "div", "innerEnd", {
                class: "Lyxintercept"
            });
            this.intercept.innerHTML = "拦截";

            this.preview = ui.addNode(button, "div", "innerEnd", {
                class: "Lyxpreview"
            });
            this.preview.innerHTML = "预览";

            var window = ui.getStyle(this.window);

            drag(title, {
                down: function()
                {
                    this.inner.x = window.right;
                    this.inner.y = window.top;
                },
                move: function()
                {
                    this.style.top = this.top;
                    this.style.left = this.left;

                    window.right = this.inner.x - this.offsetX;
                    window.top = this.inner.y + this.offsetY;
                }
            });

            drag(pointer, {
                move: function(drag)
                {
                    drag.style.top = drag.top;

                    drag.style.left = Lyx.scope(35, 441, drag.style.left);

                    this.index = Math.round((drag.style.left - 41) / layer.width);
                    drag.style.left = this.index * layer.width + 41;
                    this.pointer(this.index);
                }
            }, this);
        }

        p2t.hide = function(el)
        {
            this.window.style.display = "none";
        }

        p2t.show = function()
        {
            this.window.style.display = "";
        }

        p2t.previewMode = function(status)
        {
            this.preview.innerHTML = status ? "取消预览" : "预览";
            this.content.style.display = status ? "none" : "";
            this.select.style.display = status ? "none" : "";
        }

        p2t.selectMode = function(status)
        {
            this.content.style.display = status ? "" : "none";
            this.select.style.display = status ? "" : "none";
            this.cancelSelect.style.display = status ? "none" : "";
            this.intercept.style.display = status ? "" : "none";
            this.preview.style.display = status ? "" : "none";
        }
    });

    var Bar = Lyx.createClass(function(p2t){
        p2t.init = function(parent)
        {
            this.list = [];
            this.number = 0;
            this.width = 0;
            this.parent = parent;
        }

        p2t.setNumber = function(number)
        {
            this.number = number;
            this.width = (400 / number) - 1;
            var i = 0;
            var len = 0;
            for(len = this.list.length; i < len && i < number; i ++)
            {
                ui.css(this.list[i], {
                    width: this.width,
                    display: ""
                });
            }

            if(i < number)
            {
                for(; i < number; i ++)
                {
                    this.list.push(ui.addNode(this.parent, "div", "innerEnd", {
                        style: {
                            width: this.width
                        }
                    }));
                }
            }
            else
            {
                for(; i < len; i ++)
                {
                    ui.css(this.list[i], {
                        width: 0,
                        display: "none"
                    });
                }
            }
        }
    });

    var Border = Lyx.createClass(function(p2t){
        var body = ui.$("body[0]");

        var baseStyle = {
            position: "fixed",
            top: 0,
            left: 0,
            background: "#0af",
            zIndex: 99999
        };

        p2t.init = function()
        {
            this.list = new Lyx.queue();

            this.top = ui.addNode(body, "div", "innerEnd", {
                style: Lyx.extend({}, [baseStyle, {
                    width: 0,
                    height: 5
                }])
            });

            this.left = ui.addNode(body, "div", "innerEnd", {
                style: Lyx.extend({}, [baseStyle, {
                    width: 5,
                    height: 0
                }])
            });
            this.right = ui.addNode(body, "div", "innerEnd", {
                style: Lyx.extend({}, [baseStyle, {
                    width: 5,
                    height: 0
                }])
            });
            this.bottom = ui.addNode(body, "div", "innerEnd", {
                style: Lyx.extend({}, [baseStyle, {
                    width: 0,
                    height: 12,
                    fontSize: 10,
                    lineHeight: 12,
                    textAlign: "right",
                    color: "#fff"
                }])
            });
        };

        p2t.position = function(el)
        {
            var position = el.getBoundingClientRect();
            ui.css(this.top, {
                left: position.left,
                top: position.top - 5,
                width: position.width
            });
            ui.css(this.left, {
                left: position.left - 5,
                top: position.top - 5,
                height: position.height + 17
            });
            ui.css(this.right, {
                left: position.left + position.width,
                top: position.top - 5,
                height: position.height + 17
            });
            ui.css(this.bottom, {
                left: position.left,
                top: position.top + position.height,
                width: position.width
            });
        };

        p2t.setInnerHTML = function(el, exclude)
        {
            var str = "";
            while(el.nodeName != "BODY")
            {
                if(exclude == el)
                {
                    return false;
                }
                str = el.nodeName.toLowerCase() + " " + str;
                el = el.parentNode;
            }
            this.bottom.innerHTML = str;
            return true;
        };

        p2t.show = function()
        {
            ui.css(this.top, {
                display: ""
            });
            ui.css(this.left, {
                display: ""
            });
            ui.css(this.right, {
                display: ""
            });
            ui.css(this.bottom, {
                display: ""
            });
        };

        p2t.hide = function()
        {
            ui.css(this.top, {
                display: "none"
            });
            ui.css(this.left, {
                display: "none"
            });
            ui.css(this.right, {
                display: "none"
            });
            ui.css(this.bottom, {
                display: "none"
            });
        }
    });

    var border = Border();
    var pop = selectPop(function(index){
        border.position(border.list[index]);
        border.bottom.innerHTML = getPath(border.list, index);
    });
    var layer = Bar(pop.view);

    function getPath(list, begin)
    {
        var str = "";
        for(var i = begin || 0, len = list.length - 4; i < len; i++)
        {
            // 排除选择框
            if(list[i] == pop.window)
            {
                return false;
            }
            str += list[i].nodeName.toLowerCase() + " ";
        }
        return str;
    }
    
    function select(event)
    {
        var result = getPath(event.path);
        if(result != false)
        {
            border.bottom.innerHTML = result;
            border.position(event.target);
        }
    }

    var click = function(event)
    {
        border.list = event.path;
        layer.setNumber(event.path.length - 4);
        ctrl.select = false;
        ui.stop(event);
        pop.show();
        pop.selectMode(true);
    }

    var ctrl = {
        select: false,
        $select: {
            set: function(value, oldValue)
            {
                if(value != oldValue)
                {
                    ui.hander[value ? "add" : "remove"](document.body, "click", click);
                    ui.hander[value ? "add" : "remove"](document.body, "mouseover", select);
                    if(value)
                    {
                        border.show();
                    }
                }
            }
        },
        open: false,
        $open: {
            set: function(value, oldValue)
            {
                if(value != oldValue)
                {
                    chrome.extension.sendMessage({
                        open: value
                    });
                }
            }
        }
    }

    Lyx.observe(ctrl);
    ctrl.select = false;

    var closePop = function()
    {
        ctrl.select = false;
        pop.hide();
        border.hide();
    }

    ui.hander.add(pop.close, "click", closePop);
    
    ui.hander.add(pop.cancelSelect, "click", closePop);

    ui.hander.add(pop.select, "click", function(event){
        ctrl.select = true;
        pop.selectMode(false);
        ui.stop(event);
    });


    ui.hander.add(pop.preview, "click", function(event){
        if( border.list[pop.index].style.display == "")
        {
            border.list[pop.index].style.display = "none";
            pop.previewMode(true);
            border.hide();
        }
        else
        {
            border.list[pop.index].style.display = "";
            pop.previewMode(false);
            border.show();
        }
    });

    ui.hander.add(pop.intercept, "click", function(){
        chrome.extension.sendMessage("hellow", function(){
            console.log("不是吧");
        });
    });

    var callback = {
        open: function(value)
        {
            if(value)
            {
                border.show();
                ctrl.select = true;
            }
            else
            {
                pop.hide();
                border.hide();
            }
        }
    }

    chrome.extension.onMessage.addListener(function(obj){
        Lyx.each(obj, function(key, value){
            callback[key](value);
            console.log(key, value);
        });
    });

    ui.hander.add($("#rightKey"), "click", function(event){
        ctrl.select = true;
        ui.stop(event);
    });
});